import axios, { AxiosResponse } from 'axios';
import { z } from "zod";
import { tool } from "@langchain/core/tools";

const formatWeatherInfo = (weatherInfo) => {
    const { city, realtime, future } = weatherInfo;
    const currentWeather = `
    今天 ${city} 的天气是 ${realtime.info}，温度为 ${realtime.temperature}℃，湿度为 ${realtime.humidity}%。
    风向是 ${realtime.direct}，风力为 ${realtime.power}，空气质量指数为 ${realtime.aqi}，整体空气质量良好。
        `;

    // 提取未来天气信息
    let futureWeather = "未来几天的天气预报如下：\n";
        future.forEach(day => {
        futureWeather += `
    - ${day.date}：${day.weather}，温度范围为 ${day.temperature}，风向为 ${day.direct}。
            `;
    });

    return `${currentWeather}\n${futureWeather}`;
}

const getWeather = async ({ city }) => {
    console.log('city: ', city,)

    let result: any = null;

    const res: any = await axios.get('http://apis.juhe.cn/simpleWeather/query', {
        params: {
            city,
            key: 'b5a191454e2a387f84f7ef28a7226eb2'
        },
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    }).catch(error => {
        // 网络请求失败，可以根据实际情况进行处理
        console.log('网络请求失败:', error);
        result = {
            content: [{
                type: 'text',
                text: '网络请求失败'
            }]
        }
    });
    if ([200, 201].includes(res.status)) {
        const weatherInfo = res.data?.result;
        console.log(22, weatherInfo)
        result = {
            content: [{
                type: 'text',
                text: formatWeatherInfo(weatherInfo)
                // todo: 格式化出参
            }]
        }
    } else {
        console.log('请求异常');
        result = {
            content: [{
                type: 'text',
                text: '请求异常'
            }]
        }
    }
    console.log('result: ', result)

    return result;

}

const getWeatherTool = [
    'get_weather_info',
    '根据城市名获取天气信息',
    {
        city: z.string().describe('城市名')
    },
    getWeather

]

const getWeatherTool2 = tool(getWeather, {
    name: 'get_weather_info',
    // parameters: {
    //     type: 'object',
    //     properties: {
    //         city: {
    //             type: 'string',
    //             description: '城市名'
    //         }
    //     },
    //     required: ['city']
    // },
    schema: z.object({
        city: z.string().describe('城市名')
    }),
    description: '根据城市名获取天气信息',
})

const getWeatherSchema = {
    name: 'get_weather_info',
    description: '根据城市名获取天气信息',
    parameters: {
        type: 'object',
        properties: {
            city: {
                type: 'string',
                description: '城市名'
            }
        },
        required: ['city']
    },
    schema: z.object({
        city: z.string().describe('城市名')
    })
}

export {
    getWeather,
    getWeatherTool,
    getWeatherSchema,
    getWeatherTool2
};